﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

/// <summary>
/// Class which holds extension method for IList
/// </summary>
public static class ScrumSortExtender
{
    /// <summary>
    /// Orders the itemList by sort expression in specified order.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="itemList">The item list.</param>
    /// <param name="sortExpression">The sort expression.</param>
    /// <param name="sortDirection">The sort direction.</param>
    public static IList<T> OrderBy<T>(this IList<T> itemList, string sortExpression, SortDirection sortDirection)
    {
        Type type = typeof(T);
        System.Reflection.PropertyInfo info = type.GetProperty(sortExpression);
        IEnumerable<T> query = itemList.OrderBy(item => info.GetValue(item, null));

        IList<T> sorted = new List<T>();
        foreach (T item in query)
        {
            sorted.Insert(
                sortDirection == SortDirection.Ascending ? sorted.Count : 0
                , item
            );
        }
        return sorted;
    }
}
